package com.example.yblin.hello24.DataUtils;

import android.content.Context;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;

public class LoginUtil {
    public static final String TAG = "LoginUtil";

    private String username;
    private String password;

    public LoginUtil(String mUsername, String mPassword) {
        username = mUsername;
        password = mPassword;
    }

    /**
     * 使用本地数据自动登录
     *
     * @param context 上下文
     * @return 登录是否成功
     */
    public static int login(Context context) {
        Log.i(TAG, "自动登录:");
        Log.i(TAG, "用户名：" + LocalDataUtil.read(context, LocalDataUtil.DATABASE_USERDATA, LocalDataUtil.USERNAME));
        Log.i(TAG, "密码：" + LocalDataUtil.read(context, LocalDataUtil.DATABASE_USERDATA, LocalDataUtil.PASSWORD));
        return login(
                LocalDataUtil.read(context, LocalDataUtil.DATABASE_USERDATA, LocalDataUtil.USERNAME),
                LocalDataUtil.read(context, LocalDataUtil.DATABASE_USERDATA, LocalDataUtil.PASSWORD),
                context);
    }

    public static int login(String mUsername, String mPassword, Context context) {

        //构建列表
        Map<String, String> userInfoList = new HashMap<>();
        userInfoList.put("username", mUsername);
        userInfoList.put("pwd", mPassword);

        NetUtil netUtil = new NetUtil(NetUtil.ADDR_LOGIN, userInfoList);

        Map<String, String> returnData = netUtil.getData();
        //在此执行网络异常处理
        if (returnData.get("code").equals("" + NetUtil.CODE_OK)) {
            LocalDataUtil.write(context, LocalDataUtil.DATABASE_USERDATA, LocalDataUtil.USERNAME, mUsername);
            LocalDataUtil.write(context, LocalDataUtil.DATABASE_USERDATA, LocalDataUtil.PASSWORD, mPassword);
            return NetUtil.CODE_OK;
        } else {
            return Integer.parseInt(returnData.get("code"));
        }
    }
}
